package com.litong.litongjiaoyu.controller;

import com.alibaba.fastjson.JSONObject;
import com.litong.litongjiaoyu.annotation.IgnoreAuth;
import com.litong.litongjiaoyu.model.WXSessionModel;
import com.litong.litongjiaoyu.utils.HttpClientUtil;
import com.litong.litongjiaoyu.utils.JSONResult;
import com.litong.litongjiaoyu.utils.JsonUtil;
import com.litong.litongjiaoyu.utils.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WXLoginController
 * @Description TODO
 * @Author jingz
 * @Date 2019/7/17 19:41
 * @Version 1.0
 **/
@Log4j2
@RestController
public class WXLoginController {

    /**
     * 自定义回话对象
     */
    private  String appid="";
    private String appsecret="";

    @Autowired
    private RedisUtil redisUtil;

    @IgnoreAuth
    @ResponseBody
    @RequestMapping(value = "/wxlogin", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JSONResult wxLogin(@RequestBody JSONObject jsonObject) {
        String code = jsonObject.getString("code");
        String platform = jsonObject.getString("platform");



        log.info("开始获取openid");
        //获取需要获得openid的微信小程序appid和appsecret
        if("FrontDesk".equals(platform)){

//          前台微信小程序APPID和APPsecret
            this.appid = "wx78763b2bea2646c2";
            this.appsecret = "571a3836b6b557d2e7dc1aaeabdc0be2";
        } else if("Backstage".equals(platform)) {
            //后台微信小程序APPID和APPsecret
            this.appid = "wx6a41faf108b8ecab";
            this.appsecret = "6e9c02ef2d83dcd91a2f0e730a9aa358";
        } else{
            return JSONResult.errorMsg("platform内容不符合");
        }

        //开始获取openid
        String Url = "https://api.weixin.qq.com/sns/jscode2session?";
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", appsecret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        //传回微信服务器并接收session_key，openid
        String result = HttpClientUtil.doGet(Url, param);
        WXSessionModel model = JsonUtil.jsonToPojo(result, WXSessionModel.class);

        //存入session到redis
        redisUtil.set("user-redis-session:" + model.getOpenid(), model.getSession_key(),1000 * 60 * 60 * 2);

        return JSONResult.ok(model.getOpenid());
    }



}
